package test.marui.com.mytest.view.slideBackView.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

/**
 * Created by MR on 2019/2/20.
 */
public class SlideBackView extends View {

    private ISlideView slideView;
    private float rate = 0;     // 曲线控制点
    private ValueAnimator animator;

    public SlideBackView(Context context, @NonNull ISlideView slideView) {
        super(context);
        setSlideView(slideView);
    }

    private SlideBackView setSlideView(ISlideView view) {
        this.slideView = view;
        setLayoutParams(new SlideControlLayout.LayoutParams(view.getWidth(), view.getHeight()));
        return this;
    }

    public ISlideView getSlideView() {
        return slideView;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        slideView.onDraw(canvas, rate);
    }

    public void updateRate(float updateRate, boolean hasAnim) {
        if (updateRate > getWidth()) {
            updateRate = getWidth();
        }
        if (rate == updateRate) {
            return;
        }

        cancelAnim();
        if (!hasAnim) {
            rate = updateRate;
            invalidate();
            if (rate == 0) {
                setVisibility(GONE);
            } else {
                setVisibility(VISIBLE);
            }
            return;
        }

        animator = ValueAnimator.ofFloat(rate, updateRate);
        animator.setDuration(200);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                rate = (float) animation.getAnimatedValue();
                postInvalidate();
                if (rate == 0) {
                    setVisibility(GONE);
                } else {
                    setVisibility(VISIBLE);
                }
            }
        });
        animator.start();

    }

    private void cancelAnim() {
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        cancelAnim();
        if (rate != 0) {
            rate = 0;
            invalidate();
        }
        super.onDetachedFromWindow();
    }
}
